package cn.bdqn.utils;

import cn.bdqn.entity.DecryptInfo;
import cn.bdqn.entity.UserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.LinkedList;
import java.util.List;

/**
 * @ProjectName: ycbdqn
 * @Package: cn.bdqn.utils
 * @Author: huat
 * @Date: 2020/3/3 13:46
 * @Version: 1.0
 */
public class WXCliceUtils {
    private final static String URL="https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 获取用户的session_key和openid
     * @param appidParam  小程序appid
     * @param secretParam   小程序 secret
     * @param decryptInfo  前台登陆后获取的加密信息
     * @return 包含 session_key和openid的json对象
     */
    public static UserInfo getSessionKey(String appidParam, String secretParam, DecryptInfo decryptInfo){
        try{

            List<NameValuePair> list = new LinkedList<NameValuePair>();
            BasicNameValuePair appid = new BasicNameValuePair("appid", appidParam);
            BasicNameValuePair secret = new BasicNameValuePair("secret", secretParam);
            BasicNameValuePair js_code = new BasicNameValuePair("js_code", decryptInfo.getCode());
            BasicNameValuePair grant_type = new BasicNameValuePair("grant_type", "authorization_code");
            list.add(appid);
            list.add(secret);
            list.add(js_code);
            list.add(grant_type);

            String reslut= HttpCliceUtils.getRequest(URL,list);
            //格式化成json方便获获取sessionKey及openId
            JSONObject resultJson= JSONObject.parseObject(reslut);
            String sessionKey=(String)resultJson.get("session_key");
            String openid=(String)resultJson.get("openid");
            //解密

            String   userInfo = AesCbcUtil.decrypt(decryptInfo.getEncryptedData(),sessionKey,decryptInfo.getIv(),"UTF-8");

            //将json转换成json对象
            JSONObject userInfoJson=JSONObject.parseObject(userInfo);
            //将json转换为用户对象
            UserInfo user=JSON.parseObject(userInfo, UserInfo.class);
            user.setOpenId(openid);
            return user;
        }catch (Exception e){
            new RuntimeException(e+"解密用户信息失败");
            return null;
        }
    }
}
